package br.com.advance.automacao.web.administrativo;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.primefaces.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;

import br.com.advance.automacao.model.CLP;
import br.com.advance.automacao.model.Erro;
import br.com.advance.automacao.services.CLPService;
import br.com.advance.automacao.services.ErroService;
import br.com.advance.automacao.services.exceptions.ValidationException;
import br.com.advance.automacao.web.utils.BaseBean;

@ManagedBean
@ViewScoped
public class EditarErroMBean extends BaseBean {

	/**
	 *
	 */
	private static final long serialVersionUID = 4180491670576658298L;

	private static final Logger logger = Logger.getLogger(EditarErroMBean.class);

	@Autowired
	private ErroService erroService;

	@Autowired
	private CLPService clpService;

	private Erro erro;

	private String idErro;
	private String idCLP;

	public void initialize() {
		logger.info("initialize...");
	}

	protected boolean verificaUsuarioLogado() {
		return true;
	}

	public void initializeAfter() {
		logger.info("initialize...");
		if (StringUtils.isNotBlank(idErro)) {
			erro = erroService.buscarPorId(Long.parseLong(idErro));
		} else {
			erro = new Erro();
			erro.setClp(new CLP());
			erro.setClp(clpService.buscarPorId(Long.parseLong(idCLP)));
		}
	}

	public void salvaErro() {
		try {
			if (erro.getId() == null) {
				erroService.criar(erro);
			} else {
				erroService.atualizar(erro);
			}
		} catch (ValidationException e) {
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, e.getMessage(), null);
			FacesContext.getCurrentInstance().addMessage(null, message);
			return;
		}
		RequestContext.getCurrentInstance().closeDialog(null);
	}

	public void cancelaEdicaoErro() {
		RequestContext.getCurrentInstance().closeDialog(null);
	}

	public Erro getErro() {
		return erro;
	}

	public void setErro(Erro erro) {
		this.erro = erro;
	}

	public String getIdErro() {
		return idErro;
	}

	public void setIdErro(String idErro) {
		this.idErro = idErro;
	}

	public String getIdCLP() {
		return idCLP;
	}

	public void setIdCLP(String idCLP) {
		this.idCLP = idCLP;
	}


}
